package com.dd.edu.flashsale.service.listener;

import com.dd.edu.flashsale.service.dao.OrderDao;
import com.dd.edu.flashsale.service.entity.Order;
import com.dd.edu.flashsale.service.entity.OrderStatus;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Optional;

@Component
@RocketMQMessageListener(topic = RocketMQOrderListener.MQ_FLASHSALE_PAY, consumerGroup = "group_pay")
public class RocketMQPayListener implements RocketMQListener<String> {

    public final static String REDIS_GOODS_COUNT = "ms_goods_count";

    @Autowired
    private RedisTemplate<String, Integer> redisTemplate;

    @Autowired
    private OrderDao orderDao;

    @Override
    public void onMessage(String s) {
        System.out.println("支付超时逻辑处理...");
        // todo 支付超时逻辑处理
        final Order order = new Order();
        order.setOrderId(s);
        final Optional<Order> one = orderDao.findOne(Example.of(order));
        if (one.isPresent()) {
            final Order to = one.get();
            to.setOrderStatus(OrderStatus.CANCEL);
            orderDao.save(to);

            redisTemplate.opsForValue().increment(REDIS_GOODS_COUNT); // +1
            System.out.println("订单已取消");
        }
    }
}
